package com.hptpd.questionnairesurvey.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.hptpd.questionnairesurvey.assets.WeiXinApiUrl;
import com.hptpd.questionnairesurvey.component.Result;
import com.hptpd.questionnairesurvey.service.IWeiXinApiService;
import com.hptpd.questionnairesurvey.utils.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.util.Map;

/**
 * \* Created with IntelliJ IDEA.
 * \* Date: 2019-04-23 17:04
 * \*
 * \* Description:
 * \
 *
 * @author longwei
 */
@Service("iWeiXinApiService")
public class WeiXinApiServiceImpl implements IWeiXinApiService {
    private Logger logger = LoggerFactory.getLogger(WeiXinApiServiceImpl.class);

    @Override
    public Result getOpenid(@NotNull String code, @NotNull String secretCode, @NotNull String appid) {
        if (code.isEmpty() || secretCode.isEmpty() || appid.isEmpty()) {
            return Result.badArgumentValue();
        }
        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");
        paramMap.put("secret", secretCode);
        paramMap.put("appid", appid);
        JSONObject jsonObj;
        try {
            jsonObj = HttpUtil.doGet(WeiXinApiUrl.GET_USER_APPID, paramMap);
            logger.debug("getOpenid res data: {}", jsonObj);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return Result.fail();
        }
        return Result.ok(jsonObj);
    }
}
